#include "Server.hpp"

#include <IIOServicePool.hpp>
#include <IConnection.hpp>
#include <IConnectionFactory.hpp>

using namespace std;
using namespace boost;

Server::Server(const string& address, const string& port, IIOServicePool& ioServicePool,
	ISignal& signal, IAcceptor& acceptor, IConnectionFactory& connectionFactory)
	: m_connectionFactory(connectionFactory)
	, m_ioServicePool(ioServicePool)
	, m_signals(signal)
	, m_acceptor(acceptor)
{
	// Register to handle the signals that indicate when the server should exit.
	// It is safe to register for the same signal multiple times in a program,
	// provided all registration for the specified signal is made through Asio.
	m_signals.add(SIGINT);
	m_signals.add(SIGTERM);
#if defined(SIGQUIT)
	m_signals.add(SIGQUIT);
#endif // defined(SIGQUIT)
	m_signals.asyncWait(*this);

	m_acceptor.openBindAndListen(address, port);

	startAccept();
}

Server::~Server()
{
}

void Server::startAccept()
{
	m_newConnection.reset(m_connectionFactory.createConnection());
	m_acceptor.asyncAccept(m_newConnection, *this);
}

void Server::onAccepted(const boost::system::error_code& err)
{
	if (!err)
	{
		m_newConnection->start();
	}

	startAccept();
}

void Server::run()
{
	m_ioServicePool.run();
}

void Server::handleSignal()
{
	m_ioServicePool.stop();
}
